package com.handong.handserialprogram.module.choosering;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.CriminalEntity;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.module.base.BaseActivity;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.createmission.CreateMissionActivity;
import com.handong.handserialprogram.module.devicetask.DeviceTaskActivity;
import com.handong.handserialprogram.module.singletask.MissionActivity;
import com.handong.handserialprogram.threadpool.FindRingsThread;
import com.handong.handserialprogram.ui.radar.RadarScanView;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.UserGuideUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.handong.handserialprogram.widget.guideview.Guide;
import com.handong.handserialprogram.widget.guideview.GuideBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import static com.handong.handserialprogram.utils.AppCache.getContext;

/**
 * 加入不是本机的任务选择脚环
 */
public class ChooseRingActivity extends BaseActivity<ChooseRingPresenter> implements BaseView {

    private static final String TAG = ChooseRingActivity.class.getSimpleName();

    private RecyclerView mSetRingRV;
    private RadarScanView mRadarScan;

    private ARingAdapter mRingAdapter;

    private boolean isFirstGuide = true;
    private boolean isShowGuide = true;

    private Guide mGuideInstance;

    private String mMissID, mMissName, mMissTime,mMissCar;
    private boolean mIsJoin = false;

    private List<FootRingNewEntity> mFootRinglist;
    private ArrayList<PersonEntity> mCriminalList;
    private boolean IsFinish=false;

    @Override
    protected int getContentViewID() {
        return R.layout.activity_search_ring;
    }

    @Override
    protected ChooseRingPresenter createPresenter() {
        return new ChooseRingPresenter(this);
    }

    @Override
    protected void initViewByID() {
        initHeaderLayout(false);
        setCenterTitle("任务查找脚环");

        mSetRingRV = (RecyclerView) findViewById(R.id.searchRingRV);
        mRadarScan = (RadarScanView) findViewById(R.id.searchRingRS);
    }

    @Override
    protected void initViewDataRes() {
        Bundle bundle = getIntent().getExtras();

        if (!bundle.isEmpty()) {
            mMissID = bundle.getString(KeyConstant.MISSION_ID);
            mMissName = bundle.getString(KeyConstant.MISSION_NAME);
            mIsJoin = bundle.getBoolean(KeyConstant.IS_JOIN);
            mMissTime = bundle.getString(KeyConstant.MISSION_TIME);
            mMissCar=bundle.getString(KeyConstant.MISSION_CAR);
            ArrayList<CriminalEntity> criminalEntities=(ArrayList<CriminalEntity>)bundle.getSerializable(KeyConstant.CRIMINALS_LIST);
            mCriminalList=new ArrayList<PersonEntity>();
            for (CriminalEntity entity:
                 criminalEntities) {
                PersonEntity personEntity=new PersonEntity(entity.getPName(),entity.getPersonId());
                mCriminalList.add(personEntity );
            }
        }
        if (mIsJoin) {
            setOptionText("加入");
        } else {
            setOptionText("完成");
        }
    }



    /**
     * 是否所有犯人都已绑定脚环
     * @return 所有未绑定脚环的犯人名称，用‘,’隔开
     */
    public String isAllPersonBinded(){
        String result="";

        ArrayList<PersonEntity> nPersonList=new ArrayList<PersonEntity>();
        nPersonList.addAll(mCriminalList);
        for (FootRingNewEntity entity:
                mFootRinglist) {
                String code = entity.getCriminalId();
                if (!TextUtils.isEmpty(code)) {
                    PersonEntity hasPersonEntity = null;
                    for (PersonEntity personEntity :
                            mCriminalList) {
                        if (personEntity.getId().equals(code)){
                            hasPersonEntity = personEntity;
                        }
                    }
                    if (hasPersonEntity != null) {
                        nPersonList.remove(hasPersonEntity);
                    }
                }
        }
        if (nPersonList.size()>0) {
            for (PersonEntity entity :
                    nPersonList) {
                result += entity.getName() + ',';
            }
            result = result.substring(0,result.length() - 1);
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headerBackLayout:
                finish();
                break;

            case R.id.headerOptionLayout:
                if (mRingAdapter == null) {
                    showShortToast("还没查找到脚环");
                    return;
                }
                if (mIsJoin) {//加入任务
                    hasBindAllPerson();
                } else {
                    //绑定脚环
                    uploadPersonBindInfo();
                }
                break;
            default:
                super.onClick(v) ;
        }

    }

    /**
     * 判断当前是否已经为所有犯人绑定了脚环
     */
    public void hasBindAllPerson(){
        String noBindCriminal=isAllPersonBinded();
        if(!noBindCriminal.equals("")){
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title("提示")
                    .content("请为犯人: " + noBindCriminal +
                            "绑定脚环！")
                    .positiveColorRes(R.color.back_ground_green)
                    .positiveText(R.string.dialog_positive_text)
                    .build();
            ViewUtil.removeHomeKeyListener(dialog);
        }else{
            showJoinWarningDialog();
        }
    }

    @Override
    public void onStop(){
        super.onStop();
//        if (!IsFinish)
//        {
//            mPresenter.closeSerialPort();
//            mRadarScan.stopAnimation();
//        }

    }

    @Override
    public void onStart(){
        super.onStart();
        mPresenter.scanAroundFootRing();
        mRadarScan.startAnimation();
    }

    /**
     * 绑定或加入成功跳转到 任务界面
     */
    public void bindPersonInfoSuccess(String info) {
        dismissLoadingDialog();
        AppUtil.showShortToast(this, info);

        Bundle bundle = new Bundle();
        bundle.putString(KeyConstant.MISSION_NAME, mMissName);
        bundle.putString(KeyConstant.MISSION_TIME, mMissTime);
        bundle.putString(KeyConstant.MISSION_ID, mMissID);
        bundle.putString(KeyConstant.MISSION_CAR,mMissCar);
        openActivityFinishLast(MissionActivity.class, bundle);
    }

    /**
     * 绑定脚环失败是否重试
     */
    public void bindPersonInfoFail(String reason) {
        dismissLoadingDialog();

        AppUtil.showShortToast(this, reason);
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("上传脚环失败，是否重试？")
                .negativeText(R.string.dialog_negative_text)
                .negativeColorRes(R.color.dialog_bg)
                .positiveText(R.string.dialog_positive_again)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        showLoadDialog("正在上传脚环信息...");
                        mPresenter.uploadBingRingInfo(mMissID);
                    }
                }).build());
    }

    /**
     * 显示扫描的脚环列表
     */
    public void showFootRingList(List<FootRingNewEntity> list) {
        if (!list.isEmpty()) {
            if(mRadarScan.isShown()){
                mRadarScan.stopAnimation();
                mRadarScan.setVisibility(View.GONE);
                mSetRingRV.setVisibility(View.VISIBLE);
            }
        }else{
            if(!mRadarScan.isShown()){
                mRadarScan.startAnimation();
                mRadarScan.setVisibility(View.VISIBLE);
            }
            mSetRingRV.setVisibility(View.GONE);
        }

        mFootRinglist=list;
        if (mRingAdapter == null) {
            mRingAdapter = new ARingAdapter(mCriminalList,mFootRinglist, this);
            mSetRingRV.setLayoutManager(new LinearLayoutManager(this));
            mSetRingRV.setAdapter(mRingAdapter);
        } else {
            mRingAdapter.SetRingList(mFootRinglist);
            mRingAdapter.notifyDataSetChanged();
        }

        mSetRingRV.setVisibility(View.VISIBLE);
    }



    /**
     * 激活脚环
     */
    public void activateFootRing(String id) {
        mPresenter.activateFootRing(id);
    }
    /**
     * 激活失败
     */
    public void activateRingError(final String id) {
        dismissLoadingDialog();
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("激活脚环失败，是否重试？")
                .negativeText(R.string.dialog_negative_text)
                .negativeColorRes(R.color.dialog_bg)
                .positiveText(R.string.dialog_positive_again)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.activateFootRing(id);
                    }
                }).build());
    }

    /**
     * 激活成功
     */
    public void activateRingSuccess() {
        dismissLoadingDialog();
        showShortToast("脚环已激活");
    }
    /**
     * 休眠成功
     */
    public void logoutSuccess(String paramString) {
        //AppUtil.showShortToast(this, "脚环已休眠");

        /*Vector<FootRingNewEntity> list= new Vector<FootRingNewEntity>();
        list.addAll(SerialPortUtil.getInstance(this).getRingList());
        for (FootRingNewEntity footRingEntity:list) {
            if(footRingEntity.getRingID().equals(paramString)){
                SerialPortUtil.getInstance(this).getRingList().remove(footRingEntity);
                mFootRinglist.remove(footRingEntity);
                mRingAdapter.notifyDataSetChanged();
                if(mFootRinglist.size()==0)finish();

                int s= SerialPortUtil.getInstance(this).getRingList().size();
                JLog.d(TAG, "休眠"+paramString+":" + "size"+s);
            }
        }*/
    }
    /**
     * 休眠脚环失败
     */
    public void logoutFail(final String paramString) {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("休眠脚环失败")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText("休眠")
                .positiveColorRes(R.color.back_ground_green)
                .negativeText("直接退出")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutFootRing(paramString);
                    }
                }).onNegative(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.forceExit(paramString);
                        ChooseRingActivity.this.finish();
                    }
                }).build());
    }

    /**
     * 休眠脚环
     */
    public void showExitDialog(final String paramString) {
            ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                    .content("是否休眠"+paramString+"脚环？")
                    .negativeColorRes(R.color.dialog_bg)
                    .positiveText("休眠")
                    .positiveColorRes(R.color.back_ground_green)
                    .negativeText(R.string.dialog_negative_text)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                              mPresenter.logoutFootRing(paramString);

                        }
                    }).build());

    }

    /**
     * 脚环自检错误
     */
    public void showCheckDialog(final String paramString,final String errorString) {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("脚环"+paramString+"自检失败，详情："+errorString)
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .build());
    }

    /**
     * 休眠全部脚环弹框
     */
    protected void showExitAllDialog() {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("退出前请先休眠脚环!")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText("休眠")
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutAllFootRing();

                    }
                }).build());
    }


    /**
     * 加入脚环引导
     */
    public void showActivateGuideView(View guideView) {
        mGuideInstance = UserGuideUtil.showActivateGuideView(guideView, R.id.ringItemBtnSet, this,
                new GuideBuilder.OnVisibilityChangedListener() {
                    @Override
                    public void onShown() {
                    }

                    @Override
                    public void onDismiss() {
                        mGuideInstance = null;
                    }
                });
    }

    /**
     * 绑定脚环
     */
    public void uploadPersonBindInfo() {
        if(mPresenter.hasMyBingding()){
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title("绑定脚环")
                    .content("是否将已激活脚环信息，上传到警务平台？")
                    .positiveColorRes(R.color.back_ground_green)
                    .positiveText(R.string.dialog_positive_text)
                    .negativeColorRes(R.color.bg_gray)
                    .negativeText(R.string.dialog_negative_text)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            showLoadDialog("正在上传脚环信息...");
                            mPresenter.uploadBingRingInfo(mMissID);
                        }
                    }).build();
            ViewUtil.removeHomeKeyListener(dialog);

        }else{
            if (mPresenter.hasCanBingDing()) {
                showActivateGuideView(mRingAdapter.getActiveView(mPresenter.getNoBingdingPosstion()));
            }else AppUtil.showLengthToast(this,"没有可绑定的脚环");
        }

    }

    /**
     * 加入任务
     */
    private void showJoinWarningDialog() {
        if(mPresenter.hasMyBingding()){
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title("加入任务")
                    .content("本机设备编号: " + SPUtil.getStringValue(SPUtil.PHONE_NAME) +
                            "\n\n此操作将会加入到其他设备的任务中，是否继续？")
                    .positiveColorRes(R.color.back_ground_green)
                    .positiveText(R.string.dialog_positive_text)
                    .negativeColorRes(R.color.bg_gray)
                    .negativeText(R.string.dialog_negative_text)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                            String result=mPresenter.checkErrorFootring();
                            if (result.equals("")) {
                                IsFinish=true;
                                showLoadDialog("正在加入任务...");
                                mPresenter.requestJoinMiss(mMissID);
                            }
                            else{
                                showBindingErrorDialog(result);
                            }

                        }
                    }).build();
            ViewUtil.removeHomeKeyListener(dialog);
        }else{
            if (mPresenter.hasCanBingDing()) {
                showActivateGuideView(mRingAdapter.getActiveView(mPresenter.getNoBingdingPosstion()));
            }else AppUtil.showLengthToast(this,"没有可绑定的脚环");
        }

    }

    /**
     * 提示绑定失败提示框
     * @param ids
     */
    private void showBindingErrorDialog(String ids)
    {
        MaterialDialog mCreateDialog = new MaterialDialog.Builder(this)
                .title("绑定失败")
                .content(//"被创建的任务将不会包含押解人员、规划路线以及使用车辆。 \n\n" +
                        "脚环：" + ids + "绑定失败，请重新开锁并绑定！")
                .positiveText("确定")
                .positiveColorRes(R.color.back_ground_green)
                //.negativeText(R.string.dialog_negative_text)
                //.negativeColorRes(R.color.dialog_bg)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                }).build();
        ViewUtil.removeHomeKeyListener(mCreateDialog);
    }
    /**
     * 加入任务失败
     */
    public void joinMissionFail(String reason) {
        dismissLoadingDialog();

        AppUtil.showShortToast(this, reason);
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("加入任务失败，是否重试？")
                .negativeText(R.string.dialog_negative_text)
                .negativeColorRes(R.color.dialog_bg)
                .positiveText("再次加入")
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        showLoadDialog("正在加入任务...");
                        mPresenter.requestJoinMiss(mMissID);
                    }
                }).build());
    }

    /**
     * sim错误
     * @param missID
     */
    protected void simInitError(final String missID) {
        if (!mIsResume) {
            return;
        }
        ViewUtil.removeAllKeyListener(new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_problem)
                .content("脚环:" + missID + " 获取Sim卡信息失败\n\n请注销重新检查！")
                .positiveText(R.string.dialog_positive_sleep)
                .canceledOnTouchOutside(false)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        mPresenter.logoutFootRing(missID);
                    }
                }).build());
    }

    @Override
    public void finish() {
        if (isShowGuide && mGuideInstance != null) {
            mGuideInstance.dismiss();
            return;
        }
//        if (!mPresenter.isCanExit()) {
//            return;
//        }
        super.finish();
        overridePendingTransition(R.anim.anim_no, R.anim.push_right_out);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode && mGuideInstance != null && mGuideInstance.onKey(null, keyCode, event)) {
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (mRadarScan != null) {
            mRadarScan.stopAnimation();
            mRadarScan.onDestroy();
            mRadarScan = null;
        }
        super.onDestroy();
    }
}
